package handler

import (
	"context"
	errors2 "errors"

	"temp/auth"
	"temp/constant"
	"temp/errors"
	"temp/model"
	"temp/service"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

type UserHandler struct {
	service *service.UserService
}

func (u *UserHandler) Login(c *gin.Context) {
	var loginForm LoginRequest
	err := c.ShouldBindJSON(&loginForm)
	if err != nil {
		errors.HandlerLoginError(c)
		return
	}
	ctx := context.Background()
	token, err := u.service.Login(ctx, loginForm.UserName, loginForm.Password)
	if err != nil {
		errors.HandlerLoginError(c)
		return
	}
	c.Request.WithContext(ctx)
	constant.SuccessResult(c, gin.H{
		"token":   token,
		"expired": 72000,
	})
	return
}

func (u *UserHandler) Logout(c *gin.Context) {
	c.Request.Header.Set("Authorization", "")
	constant.SuccessResult(c, "")
	return
}

// CurrentUser 获取当前登录用户信息
func (u *UserHandler) CurrentUser(c *gin.Context) {
	user := c.Request.Context().Value("auth_user")
	if user != nil {
		errors.HandlerAuthError(c)
		return
	}
	constant.SuccessResult(c, user)
}

func (u *UserHandler) RefreshToken(c *gin.Context) {
	token := c.Request.Header.Get("Authorization")
	if token == "" {
		errors.HandlerAuthError(c)
		return
	}
	ctx := context.Background()
	newToken, err := auth.RefreshToken(token)
	if err != nil {
		errors.HandlerAuthError(c)
		return
	}
	c.Request.WithContext(ctx)
	constant.SuccessResult(c, newToken)
}

func (u *UserHandler) CreateUser(c *gin.Context) {
	var user model.User
	err := c.ShouldBindJSON(&user)
	if err != nil {
		errors.HandlerError(c, err)
		return
	}
	err = u.service.CreateUser(c.Request.Context(), user)
	if err != nil {
		errors.HandlerError(c, err)
		return
	}
	return
}
func (u *UserHandler) Register(c *gin.Context) {
	var input = struct {
		Name     string `json:"name,omitempty"`
		Password string `json:"password,omitempty"`
	}{}
	err := c.ShouldBindJSON(&input)
	if err != nil {
		errors.HandlerError(c, err)
	}
	err = u.service.Register(c.Request.Context(), input.Name, input.Password)
	if err != nil {
		errors.HandlerError(c, err)
		return
	}
	constant.SuccessResult(c, "")
}

func (u *UserHandler) Roles(c *gin.Context) {
	user := c.Param("user")
	roles := c.QueryArray("role")
	if user == "" || len(roles) == 0 {
		errors.HandlerError(c, errors2.New("user is empty"))
		return
	}
	err := u.service.Roles(c.Request.Context(), user, roles)
	if err != nil {
		errors.HandlerRolesError(c)
		return
	}
	constant.SuccessResultMsg(c)
	return
}

func NewUserHandler(db *gorm.DB, cache *redis.Client) *UserHandler {
	return &UserHandler{
		service: service.NewUserService(db, cache),
	}
}
